package code1.string;

/**
 * 原题链接：https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/
 */
public class p28 {

    //下标匹配
    public static int strStr(String haystack, String needle) {
        char[] str1 = haystack.toCharArray();    //主串
        char[] str2 = needle.toCharArray();     //子串
        //朴素匹配
        int i=0,j=0;
        while(i<str1.length && j<str2.length){
            if(str1[i]==str2[j]){
                i++;
                j++;
            }else{
                i=i-j+1;
                j=0;
            }
        }
        if(j>=str2.length){
            return i-str2.length;
        }else{
            return -1;
        }
    }

    public static void main(String[] args) {
        System.out.println(strStr("sadbutsad","sad"));
        System.out.println(strStr("leetcode", "leeto"));
    }
}
